//
//  CZContactsVC.m
//  CZWeiXin
//
//  Created by Alvechen on 16/4/12.
//  Copyright © 2016年 alvechen. All rights reserved.
//

#import "CZContactsVC.h"
#import "CZChatVC.h"


@interface CZContactsVC ()<XMPPRosterDelegate,XMPPvCardAvatarDelegate>

///联系人查询结果控制器
@property (nonatomic,strong) NSFetchedResultsController  *fetchedResultsController;

@end

@implementation CZContactsVC

- (NSFetchedResultsController *)fetchedResultsController{
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    //实例化
    
    //存储器
    XMPPRosterCoreDataStorage *storage = [XMPPRosterCoreDataStorage sharedInstance];
    
    //查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPUserCoreDataStorageObject"];
    //条件(谓词),订阅情况 none/to/from/both
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subscription == 'both'"];
    
    //排序描述器
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"jidStr" ascending:YES];
    request.sortDescriptors = @[sortDesc];
    request.predicate = predicate;
    
    //创建查询结果控制器
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:storage.mainThreadManagedObjectContext sectionNameKeyPath:@"sectionName" cacheName:nil];
    
    //执行查询
    NSError *error = nil;
    [_fetchedResultsController performFetch:&error];
    
    for (XMPPUserCoreDataStorageObject *aContacts in _fetchedResultsController.fetchedObjects) {
        
        
        //打印订阅情况
        NSLog(@"%@-%@",aContacts.jidStr,aContacts.subscription);
    }
    
    return _fetchedResultsController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self fetchedResultsController];
    
    //成为花名册模块的代理
    [[CZXMPPManager shareInstance].xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //成为个人资料头像模块代理
    [[CZXMPPManager shareInstance].xmppvCardAvatarModule addDelegate:self delegateQueue:dispatch_get_main_queue()];

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    //聊天控制器
    CZChatVC *chatVC = segue.destinationViewController;
    //获取选中的索引
    NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
    
    //取出当前选中的对应的联系人对象
    XMPPUserCoreDataStorageObject *aContacts = [self.fetchedResultsController objectAtIndexPath:indexPath];
    
    // lisi@im.zhigong.com/职工e家
    //赋值含有资源的JID给聊天控制器,若选中的联系人不在线，aContacts.primaryResource为nil
    chatVC.resourceJid = aContacts.primaryResource.jid;
    
    
    
    //赋值 不 含有资源的JID给聊天控制器
    chatVC.jid = aContacts.jid;
    
    
}

#pragma mark - funcs

- (void)fetchData{

    //重新获取数据
    [self.fetchedResultsController performFetch:nil];
    //刷新表格
    [self.tableView reloadData];
}

#pragma mark - UI事件

- (IBAction)addContacts:(id)sender {
    
    //创建要添加的好友,resource:可以不指定,哪个设备下都可以被添加
    XMPPJID *aJid = [XMPPJID jidWithUser:@"xue" domain:kCZ_DOMAIN resource:nil];
    //添加好友
    [[CZXMPPManager shareInstance].xmppRoster addUser:aJid withNickname:@"xue"];
}


#pragma mark - tableView数据源和代理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return self.fetchedResultsController.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    //取出对应组
    id<NSFetchedResultsSectionInfo> aSection = self.fetchedResultsController.sections[section];
    
    return aSection.numberOfObjects;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_contacts"];
    
    //取出数据
    XMPPUserCoreDataStorageObject *aContacts = [self.fetchedResultsController objectAtIndexPath:indexPath];
    
    
    //赋值
    //头像
    UIImageView *avatarImgV = [cell viewWithTag:100];
    
    //使用个人资料头像模块获得头像
    NSData *avatarData = [[CZXMPPManager shareInstance].xmppvCardAvatarModule photoDataForJID:aContacts.jid];
    
    if (avatarData) {
        avatarImgV.image = [UIImage imageWithData:avatarData];
    }else{
        
        //默认头像
        avatarImgV.image = [UIImage imageNamed:@"DefaultHead"];
        
    }
    
    
    //账户名
    UILabel *acountLb = [cell viewWithTag:101];
    acountLb.text = aContacts.jidStr;
    
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    return self.fetchedResultsController.sectionIndexTitles[section];
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{

    return self.fetchedResultsController.sectionIndexTitles;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{

    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //取出联系人
    XMPPUserCoreDataStorageObject *aContacts = [self.fetchedResultsController objectAtIndexPath:indexPath];

    //删除用户
    [[CZXMPPManager shareInstance].xmppRoster removeUser:aContacts.jid];
    
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{

    return @"删除";
}

#pragma mark - XMPPRosterDelegate


/**
 * 订阅关系发生改变的时候
 */
- (void)xmppRoster:(XMPPRoster *)sender didReceiveRosterPush:(XMPPIQ *)iq{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //重新显示数据
        [self fetchData];
    });
    
    
}

#pragma mark - XMPPvCardAvatarDelegate
/**
 * 收到头像更新
 */
- (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(UIImage *)photo forJID:(XMPPJID *)jid{

    //刷新数据
    [self fetchData];
    
}











@end
